package com.kaifamiao.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet( "/application/attribute/*" )
public class ApplicationAttributeServlet extends HttpServlet {

    @Override
    protected void doGet( HttpServletRequest request , HttpServletResponse response ) throws ServletException, IOException {
        // 从请求参数中获取即将被删除的 ServletContext 属性名称
        String name = request.getParameter( "name" );
        // 获得 ServletContext 对象
        ServletContext application = request.getServletContext();
        // 删除 ServletContext 对象中指定名称的属性
        application.removeAttribute( name );
        response.sendRedirect( request.getContextPath() + "/index.jsp" );
    }

    @Override
    protected void doPost( HttpServletRequest request , HttpServletResponse response ) throws ServletException, IOException {
        // 从表单中获取请求参数
        String name = request.getParameter( "name" );
        String value = request.getParameter( "value" );
        // 获得 ServletContext 对象
        ServletContext application = request.getServletContext();
        // 在 ServletContext 对象 添加属性 或 替换指定属性的值
        application.setAttribute( name , value );
        response.sendRedirect( request.getContextPath() + "/index.jsp" );
    }

}
